'use client'
import { useCallback, useEffect, useState } from 'react'
import { useContext } from 'use-context-selector'
import { RiCloseLine } from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import { ReactMultiEmail } from 'react-multi-email'
import { RiErrorWarningFill } from '@remixicon/react'
import Input from '@/app/components/base/input'
import RoleSelector from './role-selector'
import s from './index.module.css'
import cn from '@/utils/classnames'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import { inviteMember } from '@/service/common'
import { emailRegex } from '@/config'
import { ToastContext } from '@/app/components/base/toast'
import type { InvitationResult } from '@/models/common'
import I18n from '@/context/i18n'
import 'react-multi-email/dist/style.css'
import { noop } from 'lodash-es'

import { useProviderContextSelector } from '@/context/provider-context'
type IInviteModalProps = {
  isEmailSetup: boolean
  onCancel: () => void
  onSend: (invitationResults: InvitationResult[]) => void
}

const InviteModal = ({
  isEmailSetup,
  onCancel,
  onSend,
}: IInviteModalProps) => {
  const { t } = useTranslation()
  const licenseLimit = useProviderContextSelector(s => s.licenseLimit)
  const refreshLicenseLimit = useProviderContextSelector(s => s.refreshLicenseLimit)
  const [emails, setEmails] = useState<string[]>([])
  const { notify } = useContext(ToastContext)
  const [isLimited, setIsLimited] = useState(false)
  const [isLimitExceeded, setIsLimitExceeded] = useState(false)
  const [password, setPassword] = useState('')
  const [name, setName] = useState('')
  const [accountNum, setAccountName] = useState('')
  const [deptName, setDeptName] = useState('')
  const [usedSize, setUsedSize] = useState(licenseLimit.workspace_members.size ?? 0)
  useEffect(() => {
    const limited = licenseLimit.workspace_members.limit > 0
    const used = emails.length + licenseLimit.workspace_members.size
    setIsLimited(limited)
    setUsedSize(used)
    setIsLimitExceeded(limited && (used > licenseLimit.workspace_members.limit))
  }, [licenseLimit, emails])

  const { locale } = useContext(I18n)
  const [role, setRole] = useState<string>('normal')

  const handleSend = useCallback(async () => {
    if (isLimitExceeded)
      return

    const { result, invitation_results } = await inviteMember({
      url: '/workspaces/current/members/add-members',
      body: { name, role, password, dept_name: deptName, account_num: accountNum, language: 'zh-Hans' },
    })

    if (result === 'success') {
      refreshLicenseLimit()
      onCancel()
      onSend(invitation_results)
    }
  }, [isLimitExceeded, name, password, accountNum, role, deptName, locale, onCancel, onSend, notify, t])

  return (
    <div className={cn(s.wrap)}>
      <Modal overflowVisible isShow onClose={noop} className={cn(s.modal)}>
        <div className='flex justify-between mb-2'>
          <div className='text-xl font-semibold text-text-primary'>{t('common.members.inviteTeamMember')}</div>
          <RiCloseLine className='w-4 h-4 cursor-pointer text-text-tertiary' onClick={onCancel} />
        </div>


        <div>

          <div className='flex flex-col items-stretch mb-8'>
            <div className='flex'>
              <label htmlFor="accountNum" className="my-2 mr-3 text-[16px] font-base">
                账号
              </label>
              <div className="flex-1 mt-1">
                <Input
                  value={accountNum}
                  size={'large'}
                  onChange={e => setAccountName(e.target.value)}
                  id="accountNum"
                  placeholder={'输入账号' || ''}
                />
              </div>
            </div>
            <div className='flex'>
              <label htmlFor="name" className="my-2 mr-3 text-[16px] font-base">
                用户
              </label>
              <div className="flex-1 mt-1">
                <Input
                  value={name}
                  size={'large'}
                  onChange={e => setName(e.target.value)}
                  id="name"
                  placeholder={'输入用户' || ''}
                />
              </div>
            </div>
            <div className='flex'>
              <label htmlFor="deptName" className="my-2 mr-3 text-[16px] font-base">
                科室
              </label>
              <div className="flex-1 mt-1">
                <Input
                  value={deptName}
                  size={'large'}
                  onChange={e => setDeptName(e.target.value)}
                  id="deptName"
                  placeholder={'输入科室' || ''}
                />
              </div>
            </div>
            <div className='flex'>
              <label htmlFor="password" className="my-2 mr-3 text-[16px] font-base">
                密码
              </label>
              <div className="flex-1 mt-1">
                <Input
                  value={password}
                  size={'large'}
                  onChange={e => setPassword(e.target.value)}
                  id="password"
                  placeholder={'输入密码' || ''}
                />
              </div>
            </div>
            <div className='flex'>
              <label htmlFor="password" className="my-2 mr-3 text-[16px] font-base">
                角色
              </label>
              <div className="flex-1 mt-1">
                <RoleSelector value={role} onChange={setRole} />
              </div>
            </div>
          </div>

          <Button
            tabIndex={0}
            className='w-full'
            onClick={handleSend}
            disabled={!accountNum.length || !deptName.length || !name.length || !password.length || !role.length}
            variant='primary'
          >
            保存
          </Button>
        </div>
      </Modal>
    </div>
  )
}

export default InviteModal
